<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
    <PersonTable ref="asynctableRef" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { accountFormSchema } from './account.data';
  import { orgApi, userApi, getorgname } from '../system-api';
  import PersonTable from './PersonTable.vue';
  //import { setCssVar } from '/@/logics/theme/util';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { AddUserInput, UpdateUserInput, UpdateUserRoleDataInput } from '/@/api_base/models';
  import { TableActionType } from '/@/components/Table';

  export default defineComponent({
    name: 'AccountModal',
    components: { BasicModal, BasicForm, PersonTable },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const rowId = ref('');
      const { createMessage } = useMessage();
      const { info, success, warning, error } = createMessage;
      //const tableRef = ref<{ getDataSource: () => any; setColumns: (p: any) => void } | null>(null);
      const asynctableRef = ref<Nullable<TableActionType>>(null);
      //const tableSef = ref<{ setColumns: (p: any) => any } | null>(null);
      const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
        labelWidth: 100,
        schemas: accountFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        //console.log(posname);
        if (unref(isUpdate)) {
          let roleidv = []; //{posName : [142307070910548, 142307070910547],}
          const roledata = (await userApi.sysUserOwnRoleGet(data.record.id)).data.data;
          for (let t of roledata) {
            roleidv.push(t);
            //console.log(t.posId);
          }
          let roleid = { roleId: roleidv };
          console.log(roledata);
          let posidv = []; //{posName : [142307070910548, 142307070910547],}
          for (let t of data.record.sysEmpInfo.positions) {
            posidv.push(t.posId);
            //console.log(t.posId);
          }
          let posid = { posId: posidv };
          rowId.value = data.record.id;
          setFieldsValue({
            ...data.record,
            ...data.record.sysEmpInfo,
            ...posid,
            ...roleid,
          });
          //unref(asynctableRef)?.setTableData(data.record.sysEmpInfo.extOrgPos);

          //let da = [[142307070910539, 142307070910547]];
          //{posId: [142307070910547, 142307070910548]} ,

          unref(asynctableRef)?.setdatainfo(data.record.sysEmpInfo.extOrgPos);
          console.log(data.record.sysEmpInfo);
          //console.log('table data:', unref(asynctableRef)?.getDataSource());
          //console.log(data.record.sysEmpInfo.extOrgPos);
        }

        //const treeData = await orgApi.sysOrgTreeGet();
        updateSchema([
          {
            field: 'id',
            show: unref(isUpdate),
            required: unref(isUpdate),
          },
          {
            field: 'password',
            show: !unref(isUpdate),
            required: !unref(isUpdate),
          },
          {
            field: 'confirm',
            show: !unref(isUpdate),
            required: !unref(isUpdate),
          },
        ]);
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增账号' : '编辑账号'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          const extids = await unref(asynctableRef)?.getDataSource();
          const extidsdata = [];
          for (const t of extids) {
            if (t.orgId == '') {
              extidsdata.push({ orgId: +t.orgName, posId: +t.posName });
            } else {
              extidsdata.push({ orgId: +t.orgId, posId: +t.posId });
            }
          }
          //
          // TODO custom api
          const emp = {
            sysEmpParam: {
              posIdList: values.posId,
              orgId: values.orgId,
              jobNum: values.jobNum,
              extIds: extidsdata,
              orgName: await getorgname(values.orgId),
            },
          };

          let ret: any;
          if (!unref(isUpdate)) {
            const body: AddUserInput = {
              account: values.account,
              password: values.password,
              confirm: values.confirm,
              nickName: values.nickName,
              email: values.email,
              phone: values.phone,
              sex: values.sex,
              name: values.name,
              ...emp,
            };
            ret = (await userApi.sysUserAddPost(body)).data;
          } else {
            const upbody: UpdateUserInput = {
              id: values.id,
              account: values.account,
              name: values.name,
              nickName: values.nickName,
              email: values.email,
              phone: values.phone,
              sex: values.sex,
              ...emp,
            };
            ret = (await userApi.sysUserEditPost(upbody)).data;
          }

          const body: UpdateUserRoleDataInput = {
            id: values.id,
            grantRoleIdList: values.roleId,
          };
          info('授予角色：' + (await userApi.sysUserGrantRolePost(body)).data.message);

          if (ret != null) {
            if (ret.code == 204) {
              closeModal();
              success(ret.message);
            } else {
              warning(ret.message + ret.message[0].messages);
            }
          } else {
            error('未知错误');
          }

          if (unref(asynctableRef)) {
            // console.log('table data:', unref(asynctableRef)?.getDataSource());
          }

          //const [values, taskValues] = await Promise.all([validate(), validateTaskForm()]);
          //console.log('form data:', values, taskValues);

          emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit, asynctableRef };
    },
  });
</script>
